using B.S.XZYData.Api.Wrter.Application.Command.Team;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using Yitter.IdGenerator;
using TeamEntity = B.S.XZYData.Domain.XZY.Team;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Team
{
    /// <summary>
    /// 批量添加班组处理器
    /// </summary>
    public class BatchAddTeamsHandler : IRequestHandler<BatchAddTeamsCommand, ApiResult<BatchAddTeamsResult>>
    {
        private readonly IBaseRepository<TeamEntity> _teamRepo;
        private readonly ILogger<BatchAddTeamsHandler> _logger;

        public BatchAddTeamsHandler(IBaseRepository<TeamEntity> teamRepo, ILogger<BatchAddTeamsHandler> logger)
        {
            _teamRepo = teamRepo;
            _logger = logger;
        }

        public async Task<ApiResult<BatchAddTeamsResult>> Handle(BatchAddTeamsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<BatchAddTeamsResult>();
            var batchResult = new BatchAddTeamsResult();

            try
            {
                if (request.Teams == null || !request.Teams.Any())
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "没有要导入的班组数据";
                    result.Data = batchResult;
                    return result;
                }

                batchResult.TotalCount = request.Teams.Count;
                var errors = new List<string>();
                var successCount = 0;

                // 验证数据
                for (int i = 0; i < request.Teams.Count; i++)
                {
                    var team = request.Teams[i];
                    var rowNumber = i + 1;

                    // 验证必填字段
                    if (string.IsNullOrWhiteSpace(team.TeamName))
                    {
                        errors.Add($"第{rowNumber}行：班组名称不能为空");
                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(team.TeamCode))
                    {
                        errors.Add($"第{rowNumber}行：编组编码不能为空");
                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(team.TeamType))
                    {
                        errors.Add($"第{rowNumber}行：班组类型不能为空");
                        continue;
                    }

                    // 验证班组类型
                    if (!IsValidTeamType(team.TeamType))
                    {
                        errors.Add($"第{rowNumber}行：班组类型必须是：仓库、组装、机加工、注塑");
                        continue;
                    }

                    // 检查班组编码是否已存在
                    var existingTeam = await _teamRepo.GetAllAsync(x => !x.IsDeleted && x.TeamCode == team.TeamCode);
                    if (existingTeam.Any())
                    {
                        errors.Add($"第{rowNumber}行：编组编码 '{team.TeamCode}' 已存在");
                        continue;
                    }

                    // 检查班组名称是否已存在
                    var existingTeamName = await _teamRepo.GetAllAsync(x => !x.IsDeleted && x.TeamName == team.TeamName);
                    if (existingTeamName.Any())
                    {
                        errors.Add($"第{rowNumber}行：班组名称 '{team.TeamName}' 已存在");
                        continue;
                    }
                }

                // 如果有验证错误，直接返回
                if (errors.Any())
                {
                    batchResult.Errors = errors;
                    batchResult.FailCount = errors.Count;
                    result.Code = ApiEnum.Fail;
                    result.Msg = "数据验证失败";
                    result.Data = batchResult;
                    return result;
                }

                // 批量插入数据
                var teamsToAdd = new List<TeamEntity>();
                foreach (var teamModel in request.Teams)
                {
                    var team = new TeamEntity
                    {
                        Id = (int)YitIdHelper.NextId(),
                        TeamName = teamModel.TeamName.Trim(),
                        TeamCode = teamModel.TeamCode.Trim(),
                        TeamType = ParseTeamType(teamModel.TeamType),
                        Remark = teamModel.Remark?.Trim(),
                        CreateTime = DateTime.Now,
                        CreatorId = 1, // 默认创建人ID，实际应该从当前用户获取
                        IsDeleted = false
                    };
                    teamsToAdd.Add(team);
                }

                // 批量插入
                var insertResult = await _teamRepo.CreateBatchAsync(teamsToAdd);
                if (insertResult > 0)
                {
                    successCount = teamsToAdd.Count;
                    batchResult.SuccessCount = successCount;
                    batchResult.FailCount = 0;

                    result.Code = ApiEnum.Success;
                    result.Msg = $"批量导入成功！共处理{request.Teams.Count}条数据，成功{successCount}条";
                    result.Data = batchResult;

                    _logger.LogInformation($"批量导入班组成功，共{successCount}条数据");
                }
                else
                {
                    batchResult.SuccessCount = 0;
                    batchResult.FailCount = request.Teams.Count;
                    batchResult.Errors.Add("批量插入失败");

                    result.Code = ApiEnum.Fail;
                    result.Msg = "批量插入失败";
                    result.Data = batchResult;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量导入班组时发生异常");
                
                batchResult.SuccessCount = 0;
                batchResult.FailCount = request.Teams.Count;
                batchResult.Errors.Add($"系统异常：{ex.Message}");

                result.Code = ApiEnum.Fail;
                result.Msg = $"批量导入失败：{ex.Message}";
                result.Data = batchResult;
            }

            return result;
        }

        /// <summary>
        /// 验证班组类型是否有效
        /// </summary>
        private bool IsValidTeamType(string teamType)
        {
            var validTypes = new[] { "仓库", "组装", "机加工", "注塑" };
            return validTypes.Contains(teamType.Trim());
        }

        /// <summary>
        /// 解析班组类型
        /// </summary>
        private TeamTypeEnum ParseTeamType(string teamType)
        {
            return teamType.Trim() switch
            {
                "仓库" => TeamTypeEnum.Warehouse,
                "组装" => TeamTypeEnum.Assembly,
                "机加工" => TeamTypeEnum.Machining,
                "注塑" => TeamTypeEnum.InjectionMolding,
                _ => TeamTypeEnum.Warehouse // 默认值
            };
        }
    }
}
